package com.yjc.sunnyweather.ui.weather

import android.content.Context
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.WindowInsetsController
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.view.GravityCompat
import androidx.core.view.ViewCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import cn.hutool.core.date.DatePattern
import cn.hutool.core.date.DateUtil
import com.yjc.sunnyweather.ActivityCollector
import com.yjc.sunnyweather.BaseActivity
import com.yjc.sunnyweather.R
import com.yjc.sunnyweather.constant.CommonConstant
import com.yjc.sunnyweather.extension.toast
import com.yjc.sunnyweather.logic.model.Place
import com.yjc.sunnyweather.logic.model.Weather
import com.yjc.sunnyweather.logic.model.getSky
import com.yjc.sunnyweather.ui.loading.CatLoadingView
import com.yjc.sunnyweather.ui.place.PlaceViewModel
import com.yjc.sunnyweather.util.CommonUtil
import com.yjc.sunnyweather.util.LogUtil
import com.yjc.sunnyweather.util.StatusBarUtil
import kotlinx.android.synthetic.main.activity_weather.*
import kotlinx.android.synthetic.main.forecast.*
import kotlinx.android.synthetic.main.life_index.*
import kotlinx.android.synthetic.main.now.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.concurrent.thread

class WeatherActivity : BaseActivity() {

    private var isExit = false;

    var isFirst = true;

    private var placeSave: Place? = null

    val viewModel by lazy { ViewModelProvider(this).get(WeatherViewModel::class.java) }

    private val viewModelPlace by lazy { ViewModelProvider(this).get(PlaceViewModel::class.java) }

    private lateinit var mView: CatLoadingView

    private var mHandler: Handler = CommonUtil.getHandler { isExit = false }

    companion object {
        @JvmStatic
        fun actionStart(context: Context,lng: String,lat: String,name: String){
            val intent = Intent(context, WeatherActivity::class.java).apply {
                putExtra("location_lng", lng)
                putExtra("location_lat", lat)
                putExtra("place_name", name)
            }
            context.startActivity(intent)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.immersiveStatusBar(this, Color.TRANSPARENT)
        setContentView(R.layout.activity_weather)

        loadingView()

        placeSave = viewModelPlace.getSavedPlace()


        if (viewModel.locationLng.isEmpty()) {
            viewModel.locationLng = intent.getStringExtra("location_lng") ?: ""
        }
        if (viewModel.locationLat.isEmpty()) {
            viewModel.locationLat = intent.getStringExtra("location_lat") ?: ""
        }
        if (viewModel.placeName.isEmpty()) {
            viewModel.placeName = intent.getStringExtra("place_name") ?: ""
        }

        viewModel.refreshWeather(viewModel.locationLng, viewModel.locationLat)

        viewModel.weatherLiveData.observe(this, Observer { result ->
            val weather = result.getOrNull()
            if (weather != null){
                showWeatherInfo(weather)
            }else{
                val msg = "获取天气信息失败";
                msg.toast()
                result.exceptionOrNull()?.printStackTrace()
            }
            //刷新完成
            swipeRefresh.isRefreshing = false
            if (!isFirst){
                val refresh = "数据已刷新"
                refresh.toast()
            }
            //消失
            mView.dismiss();
            //isFirst
            isFirst = false
        })

        swipeRefresh.setColorSchemeResources(R.color.primaryInverseM3)
        swipeRefresh.setOnRefreshListener {
            refreshWeather()
        }

        navBtn.setOnClickListener {
            drawerLayout.openDrawer(GravityCompat.START)
        }

        drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {}

            override fun onDrawerOpened(drawerView: View) {}

            override fun onDrawerClosed(drawerView: View) {
                val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                manager.hideSoftInputFromWindow(drawerView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
            }

            override fun onDrawerStateChanged(newState: Int) {}
        })


    }

    fun loadingView(){
        mView = CatLoadingView()
        //显示
        mView.show(supportFragmentManager, "");
    }


    private fun showWeatherInfo(weather: Weather){
        placeName.text = viewModel.placeName
        val realtime = weather.realtime
        val daily = weather.daily

        // 填充now.xml布局中的数据
        val currentTempText = "${realtime.temperature.toInt()} ℃"
        currentTemp.text = currentTempText
        currentSky.text = getSky(realtime.skycon).info
        val currentPM25Text = "空气指数 ${realtime.airQuality.aqi.chn.toInt()}"
        currentAQI.text = currentPM25Text
        nowLayout.setBackgroundResource(getSky(realtime.skycon).bg)

        // 填充forecast.xml布局中的数据
        forecastLayout.removeAllViews()
        val days = daily.skycon.size
        for (i in 0 until days) {
            val skycon = daily.skycon[i]
            val temperature = daily.temperature[i]
            val view = LayoutInflater.from(this).inflate(R.layout.forecast_item,
                forecastLayout, false)
            val dateInfo = view.findViewById(R.id.dateInfo) as TextView
            val skyIcon = view.findViewById(R.id.skyIcon) as ImageView
            val skyInfo = view.findViewById(R.id.skyInfo) as TextView
            val temperatureInfo = view.findViewById(R.id.temperatureInfo) as TextView
            //val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
            val skyDate = DateUtil.format(skycon.date, DatePattern.NORM_DATE_PATTERN)
            dateInfo.text = skyDate
            val sky = getSky(skycon.value)
            skyIcon.setImageResource(sky.icon)
            skyInfo.text = sky.info
            val tempText = "${temperature.min.toInt()} ~ ${temperature.max.toInt()} ℃"
            temperatureInfo.text = tempText
            forecastLayout.addView(view)
        }
        // 填充life_index.xml布局中的数据
        val lifeIndex = daily.lifeIndex
        coldRiskText.text = lifeIndex.coldRisk[0].desc
        dressingText.text = lifeIndex.dressing[0].desc
        ultravioletText.text = lifeIndex.ultraviolet[0].desc
        carWashingText.text = lifeIndex.carWashing[0].desc
        weatherLayout.visibility = View.VISIBLE

    }

    fun refreshWeather() {
        thread{
            Thread.sleep(1000)
            runOnUiThread{
                viewModel.refreshWeather(viewModel.locationLng, viewModel.locationLat)
            }
        }
    }


    override fun onBackPressed() {
        if (placeSave != null){
            LogUtil.w("WeatherActivity","点击了back,isExit is $isExit")
            if (isExit){
                ActivityCollector.finishAll()
            }else{
                isExit = true
                CommonConstant.backMsg.toast()
                mHandler.sendEmptyMessageDelayed(1,2000)
            }
        }
    }

}